package huu.phong.googlemusic.utils;

import huu.phong.googlemusic.api.FormBuilder;
import huu.phong.googlemusic.api.IGoogleMusicAPI;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;


public final class Google {
	
	public static final String AUTH = "Auth";
	public static final String SID = "SID";
	public static final String LSID = "LSID";
	
	public static boolean isNullOrEmpty(String check) {
		return check == null || check.equals("");
	}
			
	public static Map<String, String> getLoginToken(String email, String password) throws IOException{
		URL url = new URL("https://www.google.com/accounts/ClientLogin");
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		OutputStream out = connection.getOutputStream();
		String data = String.format("accountType=GOOGLE&Email=%s&Passwd=%s&service=sj", email, password);
		out.write(data.getBytes());
		InputStream in = connection.getInputStream();
		String lines = streamToString(in);
		out.close();
		return getMap(lines);
	}
	
	public static String getCookie(String authorizationToken) throws IOException{
		URL url = new URL(IGoogleMusicAPI.HTTPS_PLAY_GOOGLE_COM_MUSIC_LISTEN);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty(IGoogleMusicAPI.GOOGLE_LOGIN_AUTH_KEY, String.format(IGoogleMusicAPI.GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
		connection.setDoOutput(true);
		OutputStream out = connection.getOutputStream();
		out.write(FormBuilder.getEmpty().getBytes());
		out.flush();
//		connection.connect();
		String cookie = connection.getHeaderField("Set-Cookie");
		connection.disconnect();
		if (cookie != null){
			int startIndex = cookie.indexOf("xt=") + 3;
			int endIndex = cookie.indexOf(";", startIndex);
			cookie = cookie.substring(startIndex, endIndex);
		}
		return cookie == null ? "" : cookie;
	}
	
	public static String getAuthLogin(String email, String password) throws IOException{
		return getLoginToken(email, password).get(AUTH);
	}
	
	public static String streamToString(InputStream in) throws IOException{
		Scanner scanner = new Scanner(in, "UTF-8").useDelimiter("\\A");
		String ret = scanner.hasNext() ? scanner.next(): "";
		in.close();
		return ret;
	}
	
	public static Map<String, String> getMap(String lines){
		Map<String, String> map = new HashMap<String, String>();
		StringTokenizer tokenizer = new StringTokenizer(lines, "\r\n=");
		while (tokenizer.hasMoreElements()){
			map.put(tokenizer.nextToken(), tokenizer.nextToken());
		}
		return map;
	}
}
